package com.affaris.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.affaris.common.Result;
import com.affaris.entity.SysFile;
import com.affaris.mapper.SysFileMapper;
import com.affaris.service.SysFileService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.reflections.vfs.SystemFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lucas
 * @since 2023-06-03
 */
@RestController
@RequestMapping("/sys-file")
public class SysFileController {

    @Autowired
    private SysFileService sysFileService;

    //上传文件
    @Value("${files.upload.path}")
    private String fileUploadPath;
    //上线项目
    @Value("${server.ip}")
    private String serverIp;


    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        //存储到磁盘中
        File uploadParentFile = new File(fileUploadPath);
        //判断
        if (!uploadParentFile.exists()) {
            uploadParentFile.mkdirs();
        }

        //文件唯一标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;
        File uploadFile = new File(fileUploadPath + fileUUID);
        //存储磁盘
        file.transferTo(uploadFile);
//        String url = "http://localhost:8090/sys-file/" + fileUUID;
        String url = "http://"+serverIp+":8090/sys-file/" + fileUUID;  //上线

        //存数据库
        SysFile saveFile = new SysFile();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize((double) size / 1024);
        saveFile.setUrl(url);
        sysFileService.save(saveFile);
        return url;
    }


    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
//        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

    /**
     * 分页查询接口
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {

        QueryWrapper<SysFile> queryWrapper = new QueryWrapper<>();
        // 查询未删除的记录
        queryWrapper.eq("is_delete", false);
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        return Result.suc(sysFileService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}
